//
//  CNGasDataManager.m
//  CarNote
//
//  Created by linshili on 13-9-17.
//  Copyright (c) 2013年 linshili. All rights reserved.
//

#import "CNGasDataManager.h"
#import "FMDatabaseQueue.h"
#import "FMDatabase.h"
#import "FMDatabaseAdditions.h"


@interface CNGasDataManager ()

@property (nonatomic, strong) FMDatabaseQueue *fmDatabaseQueue;

@end


@implementation CNGasDataManager

+ (id)shareInstance
{
    static CNGasDataManager *gasDataManager = nil;
    static dispatch_once_t onceTokenCNGasDataManager;
    dispatch_once(&onceTokenCNGasDataManager, ^{
        gasDataManager = [[CNGasDataManager alloc] init];
    });
    return gasDataManager;
}


- (id)init
{
    self = [super init];
    if (self) {
        //get database file
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *docsPath = [paths objectAtIndex:0];
        NSString *path = nil;
        NSString *userName = nil; // 将来按用户区分
        if (userName != nil) {
            NSString *dbFileName = [[NSString alloc] initWithFormat:@"CarNote.%@.db", userName];
            path = [docsPath stringByAppendingPathComponent:dbFileName];
        }
        else {
            path = [docsPath stringByAppendingPathComponent:@"CarNote.default.db"];
        }
        
        _fmDatabaseQueue = [FMDatabaseQueue databaseQueueWithPath:path];
        
        [_fmDatabaseQueue inDatabase:^(FMDatabase *db) {
            if ([db tableExists:@"GasData"] == NO) {
                
                NSString *createTableSQL = @"create table GasData(createTimestamp int primary key, fillGas float, price float,\
                    totalPay float, odometer int, isFillUp int)";
                
                if([db executeUpdate:createTableSQL]) {
                    NSLog(@"create table GasData succeed");
                }
                else {
                    NSLog(@"create table GasData failed");
                }
            }
        }];
    }
    return self;
}


- (void)dealloc
{
    [_fmDatabaseQueue close];
}


- (BOOL)saveGasInfo:(CNGasInfo *)gasInfo
{
    __block BOOL res;
    [_fmDatabaseQueue inDatabase:^(FMDatabase *db) {
        NSString *replaceSQL = [NSString stringWithFormat:@"replace into GasData(createTimestamp, fillGas, price, totalPay, odometer, isFillUp) \
                                values(?,?,?,?,?,?)"];
        
        res = [db executeUpdate:replaceSQL,
            [NSNumber numberWithUnsignedInteger:gasInfo.createTimestamp],
            [NSNumber numberWithFloat:gasInfo.fillGas],
            [NSNumber numberWithFloat:gasInfo.price],
            [NSNumber numberWithFloat:gasInfo.totalPay],
            [NSNumber numberWithInteger:gasInfo.odometer],
            [NSNumber numberWithInt:gasInfo.isFillUp]];
        
    }];
    
    return res;
}


- (NSArray *)queryGasInfoFromTimestamp:(NSUInteger)fromTimestamp toTimestamp:(NSUInteger)toTimestamp
{
    __block NSMutableArray *gasInfoArray = [[NSMutableArray alloc] init];
    [_fmDatabaseQueue inDatabase:^(FMDatabase *db) {
        
        FMResultSet *resultSet = [db executeQuery:@"select createTimestamp, fillGas, totalPay, odometer, isFillUp \
                                  from GasData where createTimestamp >= %u and createTimestamp <= %u", fromTimestamp, toTimestamp];
        
        while ([resultSet next]) {
            CNGasInfo *gasInfo = [self rowToGasInfo:resultSet];
            [gasInfoArray addObject:gasInfo];
        }
        [resultSet close];
    }];
    
    return gasInfoArray;
}


- (NSArray *)queryGasInfoFromIndex:(NSInteger)index withCount:(NSInteger)count
{
    __block NSMutableArray *gasInfoArray = [[NSMutableArray alloc] init];
    [_fmDatabaseQueue inDatabase:^(FMDatabase *db) {
        
        FMResultSet *resultSet = [db executeQuery:@"select createTimestamp, fillGas, totalPay, odometer, isFillUp \
                                  from GasData limit %d , offset %d", count, index];
        
        while ([resultSet next]) {
            CNGasInfo *gasInfo = [self rowToGasInfo:resultSet];
            [gasInfoArray addObject:gasInfo];
        }
        [resultSet close];
    }];
    
    return gasInfoArray;
}


- (CNGasInfo *)rowToGasInfo:(FMResultSet *)resultSet
{
    CNGasInfo *gasInfo = [[CNGasInfo alloc] init];
    gasInfo.createTimestamp = [resultSet intForColumn:@"createTimestamp"];
    gasInfo.fillGas = [resultSet doubleForColumn:@"fillGas"];
    gasInfo.totalPay = [resultSet doubleForColumn:@"totalPay"];
    gasInfo.odometer = [resultSet intForColumn:@"odometer"];
    gasInfo.isFillUp = [resultSet boolForColumn:@"isFillUp"];
    
    return gasInfo;
    
}

- (BOOL)deleteGasInfoWithTimestamp:(NSUInteger)timestamp
{
    __block BOOL res = NO;
    [_fmDatabaseQueue inDatabase:^(FMDatabase *db) {
        res = [db executeUpdateWithFormat:@"delete from GasData where createTimestamp = %u", timestamp];
    }];
    
    return res;
}

- (NSInteger)gasInfoCount
{
    __block NSInteger count = 0;
    [_fmDatabaseQueue inDatabase:^(FMDatabase *db) {
        count = [db intForQuery:@"select count(*) from GasData"];
    }];
    
    return count;
}

@end
